/**
 * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
 * Reserved. MIT License  (https://opensource.org/licenses/MIT)
 */
/* 2021-2023 by zhaoming,mali aihealthx.com */

function WebSocketConnectMethod(config) { //定义socket连接方法类


	var speechSokt;
	var connKeeperID;

	var msgHandle = config.msgHandle;
	var stateHandle = config.stateHandle;
	// 新增参数,统一由页面整理后带入
	var use_itn = config.use_itn;
	var asr_mode = config.asr_mode;
	var isfilemode = config.isfilemode;
	var file = config.file;
	var hotwords = config.hotwords;

	this.wsStart = function (Uri) {
		// if (Uri.match(/wss:\S*|ws:\S*/)) {
			console.log("Uri" + Uri);
		// }
		// else {
		// 	alert("请检查wss地址正确性");
		// 	return 0;
		// }

		if ('WebSocket' in window) {
			speechSokt = new WebSocket(Uri); // 定义socket连接对象
			speechSokt.onopen = function (e) { onOpen(e); }; // 定义响应函数
			speechSokt.onclose = function (e) {
				console.log("onclose ws!");
				//speechSokt.close();
				onClose(e);
			};
			speechSokt.onmessage = function (e) { onMessage(e); };
			speechSokt.onerror = function (e) { onError(e); };
			return 1;
		}
		else {
			alert('当前浏览器不支持 WebSocket');
			return 0;
		}
	};

	// 定义停止与发送函数
	this.wsStop = function () {
		if (speechSokt != undefined) {
			console.log("stop ws!");
			speechSokt.close();
		}
	};

	this.wsSend = function (oneData) {
		if (speechSokt == undefined) return;
		if (speechSokt.readyState === 1) { // 0:CONNECTING, 1:OPEN, 2:CLOSING, 3:CLOSED
			speechSokt.send(oneData);
		}
	};

	// SOCEKT连接中的消息与状态响应
	function onOpen(e) {
		console.log("WebSocket 连接已打开"); // 添加日志输出
		// 发送json
		var chunk_size = new Array(5, 10, 5);
		var request = {
			"chunk_size": chunk_size,
			"wav_name": "h5",
			"is_speaking": true,
			"chunk_interval": 10,
			"itn": use_itn,
			"mode": asr_mode,

		};
		if (isfilemode) {
			request.wav_format = file_ext;
			if (file_ext == "wav") {
				request.wav_format = "PCM";
				request.audio_fs = file_sample_rate;
			}
		}


		if (hotwords != null) {
			request.hotwords = hotwords;
		}
		console.log("发送请求:", JSON.stringify(request));
		speechSokt.send(JSON.stringify(request));
		console.log("连接成功");
		stateHandle(0);

	}

	function onClose(e) {
		console.log("WebSocket 连接已关闭"); // 添加日志输出
		stateHandle(1);
	}

	function onMessage(e) {

		try {
			console.log("Received message:", e); // 添加日志输出
			msgHandle(e); // 确保传递的是 e.data 而不是 e
		} catch (error) {
			console.error("Error handling message:", error);
		}
	}

	function onError(e) {
		console.error("WebSocket 错误:", e); // 添加日志输出
		console.log(e);
		stateHandle(2);

	}

}

export default WebSocketConnectMethod;